package com.taobaolite.search;

import com.taobaolite.item.ItemBody;
import com.taobaolite.user.store.StoreBody;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@RestController
@RequestMapping("/api/v1/search")
public class SearchController {

    private final SearchService searchService;

    public SearchController(SearchService searchService) {
        this.searchService = searchService;
    }

    @GetMapping(path = "/items")
    public List<ItemBody> searchItems(@RequestParam("item_q") String item_q) {
        List<ItemBody> ret = searchService.searchItems(item_q);
        if (ret.size() == 0) {
            throw new ResponseStatusException(
                    HttpStatus.NOT_FOUND,
                    "No item of " + item_q + " is found."
            );
        }
        return ret;
    }

    @GetMapping(path = "/stores")
    public List<StoreBody> searchStores(@RequestParam("store_q") String store_q) {
        List<StoreBody> ret = searchService.searchStores(store_q);
        if (ret.size() == 0) {
            throw new ResponseStatusException(
                    HttpStatus.NOT_FOUND,
                    "No store of " + store_q + " is found."
            );
        }
        return ret;
    }
}
